import http from "../../network/http"
import {API_CampusRoot} from "../../network/baseUrl"
import {
   GetOpenIdAndUnionIdResult, GetSubsystemBySystemId,
   LoginByUserNameAndPasswordParam, LoginByWXInfoParam,
   LoginResult,
   ResponseType,
   SchoolSimpleInfo, SubsystemInfo
} from "./types";

const bindRootPath = (path: string) => {
   return `${API_CampusRoot}${path}`
}

async function handlerResult<T>(response: Promise<ResponseType<any>>) {
   let result: ResponseType<T> = await response
   if (result.error === 0) {
      return result.data as T
   }
   throw new Error(result.msg || "服务器异常")
}

export const get = (url: string, data?: any, header?: any) => http.get(bindRootPath(url), data, header, false)
export const post = (url: string, data?: any, header?: any) => http.post(bindRootPath(url), data, header, false)
export const put = (url: string, data?: any, header?: any) => http.put(bindRootPath(url), data, header, false)
export const del = (url: string, data?: any, header?: any) => http.delete(bindRootPath(url), data, header, false)

export const getOpenIdAndUnionId = (appId: string, code: string) =>
   handlerResult<GetOpenIdAndUnionIdResult>(post("/wxUser/getUnionId", {
      AppID: appId,
      js_Code: code,
      secret: "",
      encryptedData: " ",
      iv: " "
   }))

export const getSchoolSimpleInfoList = () =>
   handlerResult<SchoolSimpleInfo[]>(get("/wxSchoolInfo/simple"))

export const loginByUserNameAndPassword = (param: LoginByUserNameAndPasswordParam) =>
   handlerResult<LoginResult>(post("/cloudLogin", param))

export const loginByWXInfo = (param: LoginByWXInfoParam) =>
   handlerResult<LoginResult>(post("/wxlogin", param))

export const getSubsystemBySystemId = (param: GetSubsystemBySystemId) =>
   handlerResult<SubsystemInfo>(get("/school/getSubsystemBySystemId", param))

export const checkPortalExist = (hostMainUrl, schoolId) => handlerResult<{ data:string }>(get(`/applet/index/hasCampusPortal`, {
   hostMainUrl,
   schoolId
}));
